package project.fileAccess;
import project.*;
import java.io.*;
import javax.swing.*;
import java.util.ArrayList;

public class AddDatabase {
public static void main(String[] args) {
DatabaseInfo dbInfo = new DatabaseInfo();
Console cons = System.console();
if (cons == null) {
    try{
        JFrame frame = new JFrame();
        dbInfo.setHostName((String)JOptionPane.showInputDialog(frame,"Host Name: ","Add a Database",JOptionPane.PLAIN_MESSAGE,null,null,""));
        dbInfo.setPortNo((Integer.parseInt((String)JOptionPane.showInputDialog(frame,"Port Number: ","Add a Database",JOptionPane.PLAIN_MESSAGE,null,null,""))));
              dbInfo.setDatabaseName((String)JOptionPane.showInputDialog(frame,"Database Name: ","Add a Database",JOptionPane.PLAIN_MESSAGE,null,null,""));
        dbInfo.setUserName((String)JOptionPane.showInputDialog(frame,"Username: ","Add a Database",JOptionPane.PLAIN_MESSAGE,null,null,""));
        dbInfo.setPassword((String)JOptionPane.showInputDialog(frame,"Password: ","Add a Database",JOptionPane.PLAIN_MESSAGE,null,null,""));
    }     catch (Exception e){
        System.err.println("Input Error");
        System.exit(1);
    }
} else {
    try{
        dbInfo.setHostName(cons.readLine("Host Name: "));
        dbInfo.setPortNo(Integer.parseInt(cons.readLine("Port Number: ")));
                  dbInfo.setDatabaseName(cons.readLine("Database Name: "));
        dbInfo.setUserName(cons.readLine("User Name: "));
        dbInfo.setPassword(cons.readPassword("Password: ").toString());
    }    catch (Exception e){
        System.err.println("Input Error");
        System.exit(1);
    }
}
ObjectInputStream inputStream = null;
ObjectOutputStream outputStream = null;
ArrayList<DatabaseInfo> dbList = new ArrayList<DatabaseInfo>();
try {
FileInputStream fileInput = new FileInputStream("locations.dat");
ObjectInputStream ois = new ObjectInputStream(fileInput);
//int j=0;

while(true){
    try{
    //j++;

    dbList.add((DatabaseInfo)ois.readObject());
    } catch (EOFException e){
    break;
    }
}
}catch (ClassNotFoundException e) {
    e.printStackTrace();
    }catch (Exception e){
    //System.err.println(e.getMessage() +j);
   
    }
dbList.add(dbInfo);
try{
FileOutputStream fileOutput = new FileOutputStream("locations.dat");
//BufferedOutputStream bos = new BufferedOutputStream( fos, 4096/* buffsize */ );
outputStream = new ObjectOutputStream(fileOutput);
for (int i =0;i<dbList.size();i++){
    outputStream.writeObject(dbList.get(i));
}
System.out.println("Add successful.");
}catch (IOException e) {
    e.printStackTrace();
}
try {
if (outputStream != null) {
    outputStream.flush();
    System.exit(1);
}
outputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}
}


}
